import tkinter as tk
import time
from pynput import keyboard


class CountdownApp:
    """倒计时应用程序类，提供计时器功能和窗口置顶功能"""
    
    def __init__(self, root):
        """初始化倒计时应用程序"""
        # 主窗口设置
        self.root = root
        self.root.title("倒计时")
        self.root.geometry("200x160")
        
        # 计时器状态变量
        self.is_running = False  # 计时器运行状态
        self.remaining_time = 180  # 默认3分钟(180秒)
        self.last_update = 0  # 上次更新时间戳
        self.after_id = None  # 存储after任务的ID，用于取消待执行的任务
        self.is_always_on_top = False  # 窗口置顶状态

        # 创建主界面元素
        self._create_widgets()
        
        # 启动热键监听
        self._start_hotkey_listener()

    def _create_widgets(self):
        """创建应用程序的所有界面元素"""
        # 倒计时显示标签
        self.time_label = tk.Label(self.root, text="3:00", font=("Arial", 48))
        self.time_label.pack(pady=(25,10))

        # 置顶按钮(左上角)
        self.topmost_btn = tk.Button(self.root, text="置顶", command=self.toggle_always_on_top, width=4)
        self.topmost_btn.place(x=0, y=0)

        # 控制按钮框架
        self.control_frame = tk.Frame(self.root)
        self.control_frame.pack()

        # 控制按钮
        self.start_btn = tk.Button(self.control_frame, text="开始", command=self.start_timer)
        self.start_btn.grid(row=0, column=0, padx=1)

        self.pause_btn = tk.Button(self.control_frame, text="暂停", command=self.pause_timer, state=tk.DISABLED)
        self.pause_btn.grid(row=0, column=1, padx=1)

        self.reset_btn = tk.Button(self.control_frame, text="重置", command=self.reset_timer)
        self.reset_btn.grid(row=0, column=2, padx=1)

    def _start_hotkey_listener(self):
        """启动热键监听线程"""
        self.listener = keyboard.Listener(on_press=self.on_key_press)
        self.listener.start()

    def toggle_always_on_top(self):
        """切换窗口置顶状态"""
        self.is_always_on_top = not self.is_always_on_top
        self.root.attributes('-topmost', self.is_always_on_top)
        # 更新按钮文本以反映当前状态
        self.topmost_btn.config(text="取消" if self.is_always_on_top else "置顶")

    def on_key_press(self, key):
        """处理按键事件，F2键重新开始计时"""
        try:
            if key == keyboard.Key.f2:
                self.reset_timer()
                self.is_running = False
                self.start_timer()
        except Exception as e:
            print(f"热键监听错误: {e}")

    def update_display(self):
        """更新倒计时显示文本"""
        mins, secs = divmod(self.remaining_time, 60)
        self.time_label.config(text=f"{mins:02d}:{secs:02d}")

    def start_timer(self):
        """开始计时器"""
        if not self.is_running:
            self.is_running = True
            self.start_btn.config(state=tk.DISABLED)
            self.pause_btn.config(state=tk.NORMAL)
            self.last_update = time.time()
            self.run_timer()

    def run_timer(self):
        """计时器核心逻辑，每秒更新倒计时"""
        if self.is_running and self.remaining_time > 0:
            now = time.time()
            elapsed = now - self.last_update
            self.last_update = now
            self.remaining_time = max(0, self.remaining_time - int(elapsed))
            self.update_display()
            # 安排下一次更新
            self.after_id = self.root.after(1000, self.run_timer)
        elif self.remaining_time <= 0:
            self.time_up()

    def reset_timer(self):
        """重置计时器到初始状态"""
        self.is_running = False  # 停止计时
        # 取消已安排的after任务（如果有）
        if self.after_id:
            self.root.after_cancel(self.after_id)
            self.after_id = None
        self.remaining_time = 180  # 重置为3分钟
        self.update_display()
        # 重置按钮状态
        self.start_btn.config(state=tk.NORMAL)
        self.pause_btn.config(state=tk.DISABLED)
        self.last_update = time.time()  # 重置时间戳

    def pause_timer(self):
        """暂停计时器"""
        self.is_running = False
        # 取消已安排的after任务（如果有）
        if self.after_id:
            self.root.after_cancel(self.after_id)
            self.after_id = None
        # 更新按钮状态
        self.start_btn.config(state=tk.NORMAL)
        self.pause_btn.config(state=tk.DISABLED)
        # 更新时间戳，确保下次开始时计算正确
        self.last_update = time.time()

    def time_up(self):
        """计时结束处理"""
        self.is_running = False
        self.reset_timer()


if __name__ == "__main__":
    # 应用程序入口
    root = tk.Tk()
    app = CountdownApp(root)
    root.mainloop()